<?php


namespace app\home\controller;


use app\base\BaseController;
use app\home\model\InReceiptDetail;
use app\home\model\TransferOrderDetail;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class TransferOrder
 * @package app\home\controller
 * 调拨单
 */
class TransferOrder extends BaseController
{
    protected $table='transfer_order';
    protected $title='调拨单';
    private $sessionKey='pageTransferOrder';


    /**
     * date:2024/3/21
     * 列表
     */
    public function index()
    {
        $param=$this->param;
        if (request()->isAjax()) {

            $where[]=['to.status','>',-1];
            foreach (['w_name','u_name'] as $i){
                if (isset($param[$i])&&$param[$i]){
                    $k=str_replace('_','.',$i);
                    $where[]=[$k,'like','%'.$param[$i].'%'];
                }
            }
            if (isset($param['i_incomTime'])&&$param['i_incomTime']){
                $times=explode('~',$param['i_incomTime']);
                $where[]=['i.incomTime','between',$times];
            }
            session($this->sessionKey,$where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)->alias('to')
                ->where($where)
                ->join('admin u','u.id=to.transfer_user','left')
                ->join('warehouse w','w.id = to.warehouse_id')
                ->field("to.*,w.name as wName,u.name as username")
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            $warehouseList=Db::name('warehouse')->where('status',1)->field('id,name')->select();
            View::assign('warehouseList',$warehouseList);
            return view();
        }

    }

    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * date:2024/3/21
     * 添加
     */
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $postData=$this->param;
            $mxid=$postData['mxid']??[];
            $material_id=$postData['material_id']??[];
//            $out_locator=$postData['out_locator']??[];
            $warehouse_id=$postData['warehouse_id']??'';
            $num=$postData['num']??[];
            $transferNum=$postData['transferNum']??[];
            $in_id=$postData['in_id']??[];
//            $in_locator=$postData['in_locator']??[];

            $param=[
                'transferTime'=>$postData['transferTime'],
                'status'=>$postData['status'],
                'warehouse_id'=>$warehouse_id,
                'id'=>$postData['id']??0,
            ];
            if (!$material_id||!$warehouse_id){
                return to_assign(1,'参数缺失');
            }
            if (in_array($warehouse_id,$in_id)){
                return to_assign(1,'禁止仓库自调');
            }
            Db::startTrans();
            $param['update_time']=time();
            $id=$param['id']??0;
            try {
                if ($param['id'] > 0) {
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $postData,$this->title);
                } else {
                    $param['create_time'] = time();
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $id, $postData,$this->title);
                }
                foreach ($material_id as $k=>$v){
                    if (empty($num[$k])||empty($transferNum[$k])
                        ||empty($in_id[$k])){
                        throw new Exception('参数有误');
                    }
                    if ($num[$k]<$transferNum[$k]){
                        throw new Exception('库存数量小于调拨数量');
                    }
                    $mxData=[
                        'material_dossier_id'=>$material_id[$k],
                        'out_id'=>$warehouse_id,
                        'out_locator'=>1,
                        'in_id'=>$in_id[$k],
                        'in_locator'=>1,
                        'num'=>$num[$k],
                        'transferNum'=>$transferNum[$k],
                        'transfer_order_id'=>$id,
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];

                    if (isset($mxid[$k])&&$mxid[$k]){
                        unset($mxData['create_time']);
                        $mxData['id']=$mxid[$k];
                    }
                    Db::name('transfer_order_detail')->save($mxData);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->field("*,(select name from fy_admin a where a.id=transfer_user)username")->find();
                View::assign('detail', $detail);
                $mxList=TransferOrderDetail::alias('tod')
                    ->join('material_dossier md','md.id=tod.material_dossier_id')
                    ->where('tod.transfer_order_id',$id)
                    ->where('tod.status',1)
                    ->with(['outLocator','inLocator'])
                    ->field("md.bar_code,md.name,md.specs,md.brand,md.unit,tod.*")->select();
                View::assign('mxList', $mxList);
            }
            $warehouseList=Db::name('warehouse')->where('status',1)->field('id,name')->select();
            View::assign('warehouseList',$warehouseList);
            View::assign('id', $id);
            View::assign('defalutTime', date('Y-m-d'));

            return view('form');
        }
    }

    public function addMx()
    {
        if (request()->isPost()) {
            $wId=$this->param['wId']??'';
            if (!$wId){
                return to_assign(1,'请选择仓库');
            }
            $where[]=['wId','=',$wId];
            foreach (['bar_code','name','specs','brand'] as $v){
                if (isset($this->param[$v])&&$this->param[$v]){
                    $where[]=[$v,'like','%'.$this->param[$v].'%'];
                }
            }
            $limit=$this->param['limit']??10;
            $list=Db::name('material_kucun_view')->where($where)->paginate($limit)->each(function ($item){
                $item['countNum']=$item['countNum']??0;
                $item['sendNum']=$item['sendNum']??0;
                $item['hadNum']=$item['countNum']-$item['sendNum'];
                return $item;
            });
            View::assign('list',$list);
            return table_assign(0, '', $list);
        } else {
            return \view('mx');
        }

    }
    public function removeMx()
    {
        $id=$this->param['id'];
        try {
            Db::name('transfer_order_detail')->where('id',$id)->update(['status'=>-1,'update_time'=>time(),'deleted'=>time()]);
            add_log('add', $id, $this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1,'删除失败:'.$e->getMessage());
        }
        return to_assign();
    }
    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $info=Db::name($this->table)->where('id',$id)->find();
        if (!$info){
            return to_assign(1,'参数有误');
        }
//        $wCode=Db::name('warehouse')->where('id',$info['warehouse_id'])->value('wCode');

        $mx=Db::name('transfer_order_detail')->where('status',1)->where('transfer_order_id',$id)->select()->toArray();
        if (!$mx){
            return to_assign(1,'请添加明细');
        }
        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update(['transfer_user'=>$this->uid,'status'=>2,'update_time'=>time(),'checkTime'=>time()]);
          $rukuData=[
              'type'=>'调拨入库',
              'transfer_order_id'=>$id,
              'incom_user'=>$this->uid,
              'create_user'=>$this->uid,
              'orderNum'=>$ordernum=dJBHBySql('in_receipt','orderNum','A'),
              'incomTime'=>date('Y-m-d'),
              'checkTime'=>time(),
              'status'=>'2',
              'create_time'=>time(),
              'update_time'=>time(),
          ];
          $chukuData=[
              'type'=>'调拨出库',
              'transfer_order_id'=>$id,
              'out_user'=>$this->uid,
              'create_user'=>$this->uid,
//              'orderNum'=>$ordernum=dJBHBySql('out_receipt','orderNum',$wCode),
              'orderNum'=>$ordernum=dJBHBySql('out_receipt','orderNum','A'),
              'outTime'=>date('Y-m-d'),
              'checkTime'=>time(),
              'status'=>'2',
              'create_time'=>time(),
              'update_time'=>time(),
          ];
          $rukuId=Db::name('in_receipt')->insertGetId($rukuData);
          $chukuId=Db::name('out_receipt')->insertGetId($chukuData);
            $rukuMx=[];
            $chukuMx=[];
            $wid=0;
           foreach ($mx as $v){
               if (!$wid){
                   $wid=$v['in_id'];
               }
               $rukuMx[]=[
                   'in_receipt_id'=>$rukuId,
                   'warehouse_id'=>$v['in_id'],
                   'transfer_order_detail_id'=>$v['id'],
                   'locator'=>$v['in_locator'],
                   'num'=>$v['transferNum'],
                   'status'=>'2',
                   'material_dossier_id'=>$v['material_dossier_id'],
                   'create_time'=>time(),
                   'update_time'=>time(),
               ];
//               Db::name('in_receipt_detail')->insertGetId($rukuMx);
               $chukuMx[]=[
                   'out_receipt_id'=>$chukuId,
                   'transfer_order_detail_id'=>$v['id'],
                   'num'=>$v['transferNum'],
                   'warehouse_id'=>$info['warehouse_id'],
                   'material_dossier_id'=>$v['material_dossier_id'],
                   'status'=>'2',
                   'create_time'=>time(),
                   'update_time'=>time(),
               ];
//               Db::name('out_receipt_detail')->insertGetId($chukuMx);

           }
//            $wCode1=Db::name('warehouse')->where('id',$wid)->value('wCode');
//            $ordernum1=dJBHBySql('in_receipt','orderNum',$wCode1);
//            Db::name('in_receipt')->where('id',$rukuId)->update(['orderNum'=>$ordernum1]);
            Db::name('in_receipt_detail')->insertAll($rukuMx);
            Db::name('out_receipt_detail')->insertAll($chukuMx);
            add_log('check', $id, $this->param,$this->title);
           Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $status=Db::name($this->table)->where('id','in',$id)->column('status');
            if (in_array('2',$status)){
                return  to_assign(1, "有已确认数据，不能删除");
            }
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                Db::name('transfer_order_detail')->where('transfer_order_id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/4/1
     * 启用/禁用
     */
    public function reuse()
    {
        $param = get_params();
        $param['update_time']=time();
        $res = Db::name($this->table)->strict(false)->field('id,status,update_time')->update($param);
        if ($res) {
            if($param['status'] == 2){
                add_log('disable', $param['id'], $param,$this->title);
            }
            else if($param['status'] == 1){
                add_log('recovery', $param['id'], $param,$this->title);
            }
            return to_assign();
        }
        else{
            return to_assign(0, '操作失败');
        }
    }

    public function importData()
    {
        Db::startTrans();
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $importData = [];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                $wIds=[];
                $times=[];
                $nums=[];
                $inIds=[];
                $mdIds=[];
                for ($j = 2; $j <= $highestRow; $j++) {
                    $wId=$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
                    $wid=Db::name('warehouse')->where('status',1)->where('id',$wId)->value('id');
                    if (!$wid){
                        throw new Exception('仓库不存在,行:'.($j-1));
                    }
                    $time=$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
//                    $time=str_replace('/','-',$time);
                    if (!$time){
                        throw new Exception('时间有误,行:'.($j-1));
                    }
                    $barCode=$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getFormattedValue();
                    $mdId=Db::name('material_kucun_view')->where('bar_code',$barCode)->where('wId',$wid)->value('mdId');
                    if (!$mdId){
                        throw new Exception($barCode.'：该物料未入库,行:'.($j-1));
                    }
                    $num=(int)$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getFormattedValue();
                    if (!$num){
                        throw new Exception('数量填写有误,行:'.($j-1));
                    }
                    $inWId=$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getFormattedValue();
                    $inid=Db::name('warehouse')->where('status',1)->where('id',$inWId)->value('id');
                    if (!$inid){
                        throw new Exception('入库仓库有误,行:'.($j-1));
                    }
                    $wIds[]=$wId;
                    $times[]=str_replace('/','-',$time);
                    $mdIds[]=$mdId;
                    $nums[]=$num;
                    $inIds[]=$inWId;
                }
                $data=$this->createImData($wIds,$times,$mdIds,$nums,$inIds);
                if ($data['code']!=200){
                    throw new Exception($data['msg']);
                }
                $res=$data['data'];
                $tData=$res['tData'];
                $detail=$res['detail'];
                $transfer_order_id=Db::name($this->table)->insertGetId($tData);
                foreach ($detail as &$v){
                    $v['transfer_order_id']=$transfer_order_id;
                }
                Db::name('transfer_order_detail')->insertAll($detail);
//                if ($importData){
//                    Db::name($this->table)->insertAll($importData);
                    add_log('import', '', $res,$this->title);
//                }

                Db::commit();
            }
        }catch (Exception $e){
            Db::rollback();
            add_log('import', '', $e->getMessage(),$this->title);
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();

    }

    public function createImData($wIds,$times,$mdIds,$nums,$inIds)
    {
        $wIds1=array_unique($wIds);
        $times1=array_unique($times);
        if (count($wIds1)!=1){
            return ['code'=>400,'仓库Id填写有误'];
        }
        $wid=$wIds1[0];
        if (count($times1)!=1){
            return ['code'=>400,'调拨时间填写有误'];
        }
        $time=$times1[0];
        $deData=[];
        foreach ($mdIds as $k=> $c){
            $dKey=$c.'_'.$inIds[$k];
            if (isset($deData[$dKey])){
                $deData[$dKey]+=$nums[$k];
            }else{
                $deData[$dKey]=$nums[$k];
            }
        }
        $tData=[
            'warehouse_id'=>$wid,
            'transferTime'=>$time,
            'tOrderNum'=>$this->getDJBHBuySql($this->table,'tOrderNum'),
            'status'=>1,
            'deleted'=>0,
            'create_time'=>time(),
            'update_time'=>time()
        ];
        $detailData=[];
        foreach ($deData as $d=>$v){
            $kData=explode('_',$d);
            $mid=$kData[0];
            $oid=$kData[1];
            $mdInfo=Db::name('material_kucun_view')->where('mdId',$mid)
                ->where('wId',$wid)->field('countNum,sendNum')->find();
            $haveNum=$mdInfo['countNum']-$mdInfo['sendNum'];
            $detailData[]=[
                'material_dossier_id'=>$mid,
                'out_id'=>$wid,
                'out_locator'=>'1',
                'in_id'=>$oid,
                'in_locator'=>'1',
                'num'=>$haveNum??0,
                'transferNum'=>$v,
                'status'=>1,
                'deleted'=>0,
                'create_time'=>time(),
                'update_time'=>time()
            ];
        }

        return ['code'=>200,'msg'=>'ok','data'=>['tData'=>$tData,'detail'=>$detailData]];
    }

    public function exportData()
    {
        $where=session($this->sessionKey);
        $list = Db::name($this->table)->alias('to')
            ->where($where)
            ->join('admin u','u.id=to.transfer_user','left')
            ->join('warehouse w','w.id = to.warehouse_id')
            ->field("to.*,w.name as wName,u.name as username")
            ->select()->each(function ($item){
                $item['status']=$item['status']==1?'草稿':'已确认';
                return $item;
            });
        $title = [
            'id' => 'ID',
            'wName' => '调出仓库',
            'username' => '调拨人',
            'transferTime' => '调拨时间',
            'status' => '状态',
        ];
        $name =$this->title;
        exportXlsData($name,$title,$list);
        exit();
    }
}